//
// Created by rany on 1/18/17.
//
#include <stdlib.h>
#include <string.h>

#include "user.h"

userList_t * initUserList()
{
    userList_t * userList = (userList_t *) malloc(sizeof(userList_t));

    if (userList != NULL) {
        userList->count = 0;
        userList->users = NULL;
    }

    return userList;
}

void insertUser(userList_t * list, user_t user)
{
    if (list == NULL) {
        return;
    }

    struct UserNode * u = (struct UserNode *) malloc(sizeof(struct UserNode));
    u->next = NULL;

    memcpy((void *) &u->user, (void *) &user, sizeof(user));

    if (list->users == NULL) {
        list->users = u;
    } else {
        list->users->next = u;
    }
}

void deleteUser(userList_t * list, user_t user)
{
    deleteUserByName(list, user.name);
}

void deleteUserByName(userList_t * list, char * name)
{
    struct UserNode * node, * tmp;

    if (list == NULL) {
        return;
    }

    node = list->users;
    tmp = node;

    while (node != NULL) {
        if (strcmp(node->user.name, name) == 0) {
            break;
        }

        tmp = node;
        node = node->next;
    }

    if (node != NULL) {
        if (list->users != node) {
            tmp->next = node->next;
        } else {
            list->users = NULL;
        }

        free(node);
    }

}

user_t getUser(userList_t * list, char * username)
{
    user_t u;
    struct UserNode * node = searchNode(list, username);

    if (node == NULL) {
        u.id = -1;
    } else {
        memcpy((void *) &u, (void *)&node->user, sizeof(node->user));
    }

    return u;
}

struct UserNode * searchNode(userList_t * list, char * name)
{
    if (list == NULL) {
        return NULL;
    }

    struct UserNode * node = list->users;

    while (node != NULL) {
        if (strcmp(node->user.name, name) == 0) {
            break;
        }

        node = node->next;
    }

    return node;
}
